<?php
namespace app\admin\controller;

use think\Request;
use app\admin\model\Admin;

class Core extends Common
{
    //系统用户
    public function user()
    {
        $adminModel = new Admin();
        $lists = $adminModel->getAllLists();
        $this->assign('lists', $lists);
        return $this->fetch();
    }

    //添加系统用户
    public function userAdd(Request $request)
    {
        if ($request->isPost()) {
            $user_id = $request->param('id', 0, 'intval');
            $user_name = $request->post('username', '', 'filterString');
            $password = $request->post('password');
            if (!$user_name) {
                $this->error('请输入用户名');
            } elseif (mb_strlen($user_name) > 10) {
                $this->error('用户名过长');
            }
            $adminModel = new Admin();
            $stat = $adminModel->userEdit([
                'user_name' => $user_name,
                'password'  => $password
            ], $user_id);
            $msg = $user_id ? '编辑' : '新增';
            if ($stat) {
                $this->success("用户{$msg}成功");
            } else {
                $this->error("用户{$msg}失败");
            }
        }
        return $this->fetch();
    }

    //修改用户
    public function userEdit(Request $request)
    {
        $adminModel = new Admin();
        $user_id = $request->param('id', 0, 'intval');
        if (!$user_id) {
            $this->error('参数错误');
        }
        $user_info = $adminModel->getInfoByField('id', $user_id);
        if (!$user_info) {
            $this->error('未查找到该用户');
        }
        $this->assign('info', $user_info);
        return $this->fetch('userAdd');
    }

    //删除用户
    public function userDelete(Request $request)
    {
        $adminModel = new Admin();
        $user_id = $request->param('id', 0, 'intval');
        if (!$user_id) {
            $this->error('参数错误');
        }
        if ($adminModel->userDel($user_id)) {
            $this->success('用户删除成功');
        } else {
            $this->error('用户删除失败');
        }
    }

    //更改用户状态
    public function userUpstatus(Request $request)
    {
        $adminModel = new Admin();
        $user_id = $request->param('id', 0, 'intval');
        if (!$user_id) {
            $this->error('参数错误');
        }
        if ($adminModel->userUpStatus($user_id)) {
            $this->success('用户状态更新成功');
        } else {
            $this->error('用户状态更新失败');
        }
    }
}
